package mxmf.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import chances.smart.commons.aspect.log.entity.Oplog;
import chances.smart.commons.json.ObjectMapperHelper;

@Component
public class LogSender {

    private static final Logger logger = LoggerFactory.getLogger(LogSender.class);

    @Autowired(required = false)
    private RabbitTemplate rabbitTemplate;

    @Value("${chances.message.log.exchange-name:log-exchange}")
    private String logExchange;

    @Value("${chances.message.log.route-key:log.cms}")
    private String routeKey;

    @Value("${chances.message.log.queue-on:false}")
    private boolean mqOn;

    @Async
    @EventListener
    public void sendLog(Oplog log) {
        if (mqOn && rabbitTemplate != null) {
            try {
                CorrelationData correlationData = new CorrelationData(log.getLogId());
                MessageProperties messageProperties = new MessageProperties();
                messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
                ObjectMapper mapper = ObjectMapperHelper.createObjectMapper();
                String body = mapper.writeValueAsString(log);
                Message message = MessageBuilder.withBody(body.getBytes("UTF-8"))
                        .setContentType(MessageProperties.CONTENT_TYPE_JSON).build();
                rabbitTemplate.convertAndSend(logExchange, routeKey, message, correlationData);
            } catch (Exception e) {
                logger.error(e.toString(), e);
            }

        }
    }
}
